//
//  HomePictureView.swift
//  JKWeiBo
//
//  Created by 王冲 on 2017/12/17.
//  Copyright © 2017年 希爱欧科技有限公司. All rights reserved.
//

import UIKit
import SDWebImage

let HomePhotoBrowser = "HomePhotoBrowser"
let HomePhotoBrowserIndexkey = "HomePhotoBrowserIndexkey"
let HomePhotoBrowserPicurekey = "HomePhotoBrowserPicurekey"

class HomePictureView: UICollectionView {
    
    var homeViewModel: HomeViewModel? {
        didSet {
            
            // sizeToFit()
            // 刷新视图
            reloadData()
        }
    }
    
//    override func sizeThatFits(_ size: CGSize) -> CGSize {
//        return calculateImageSize3()
//    }
    
    // 图片布局
    private var pictureLayout: UICollectionViewFlowLayout = HomePictureViewlayout()
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        // 提示：调用父类的构造函数之前，必须给本类的属性初始化
        super.init(frame: frame, collectionViewLayout: pictureLayout)
        
        // 1.注册可重用cell
        register(HomePictureCell.self, forCellWithReuseIdentifier: JKPictureCellReuseIdentifier)
        
        // 2.设置数据源代理
        dataSource = self
        delegate = self
        
        // 3.设置其它属性
        backgroundColor = UIColor.white
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
    /*
     0.没有图片, 返回zero
     1.单张图片, 返回图片实际大小
     2.多张图片, 图片大小固定
     2.1四张图片, 会按照田字格显示
     2.2其它多图, 按照九宫格显示
     */
     func calculateImageSize3() -> CGSize{
        
        // 0.获取图片的数量
        let count = homeViewModel?.storedPic_urls?.count
        let itemSize = CGSize(width: 90, height: 90)
        let margin:CGFloat = 10
        pictureLayout.itemSize = itemSize
        // 1.没有图片
        if count == 0 || count == nil
        {
            return CGSize.zero
        }
        // 2.单张图片
        if count == 1
        {
          // 2.1从缓存中拿到图片
            let key = homeViewModel!.storedPic_urls?.first?.absoluteString
            let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: key!)
            if image == nil
            {
                pictureLayout.itemSize = itemSize
                return itemSize
            }
            
          // 2.2返回大小
          pictureLayout.itemSize = (image?.size)!
          return image!.size
        }
        // 3.四张图片
        if count == 4
        {
            let width = itemSize.width * CGFloat(2) + margin
            return CGSize(width: width, height: width)
        }
        // 4.其它多图
        /*
         2,3 -> 1
         5,6 -> 2
         7,8,9 -> 3
         */
        let colCount = 3
        let rowCount = (count! - 1) / 3 + 1
        // 宽度 * 列数 + (列数 - 1) * 间隙
        let width = itemSize.width * CGFloat(colCount) + CGFloat(colCount - 1) * margin
        // 高度 * 行数 + (行数 - 1) * 间隙
        let height = itemSize.height * CGFloat(rowCount) + CGFloat(rowCount - 1) * margin
        return CGSize(width: width, height: height)
    }
}
let JKPictureCellReuseIdentifier = "JKPictureCellReuseIdentifier"
extension HomePictureView: UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout
{
    // MARK: - UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return homeViewModel?.storedPic_urls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // 1.取出cell
        let itemCell = collectionView.dequeueReusableCell(withReuseIdentifier: JKPictureCellReuseIdentifier, for: indexPath) as! HomePictureCell
        // 2.设置图片
        itemCell.imageURL = homeViewModel?.storedPic_urls![indexPath.item]
        itemCell.backgroundColor = UIColor.yellow
        // 3.返回cell
        return itemCell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        //print("点击的第几个cell=\(indexPath.item)")
        //print("点击的第几个cell的url=\(String(describing: homeViewModel?.storedPic_urls![indexPath.item] as URL?))")
        
        let info = [HomePhotoBrowserIndexkey : indexPath, HomePhotoBrowserPicurekey : homeViewModel!.storedLargePic_urls!] as [String : Any]
        // 发送通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: HomePhotoBrowser), object: self, userInfo: info)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        
        return UIEdgeInsets(top: 0, left:0, bottom: 0, right: 0)
    }
}

private class HomePictureCell: UICollectionViewCell {
    var imageURL: NSURL?{
        didSet{
            
            iconView.sd_setImage(with: imageURL as URL?, placeholderImage: UIImage(named:"pic_background"))
            iconView.width = self.width
            iconView.height = self.height
            
            gificonView.x = self.width-30
            gificonView.y = self.height-30
            
            if (imageURL!.absoluteString! as NSString).pathExtension.lowercased() == "gif"
            {
                gificonView.isHidden = false
            }else{
                 gificonView.isHidden = true
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(iconView)
        iconView.addSubview(gificonView)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var iconView: UIImageView = {
        
        let iconImage = UIImageView()
        iconImage.x = 0
        iconImage.y = 0
        iconImage.contentMode = UIViewContentMode.scaleAspectFill
        iconImage.clipsToBounds = true
        return iconImage
        
    }()
    
    // gif图片
    lazy var gificonView: UIImageView = {
        
        let iconImage = UIImageView()
        iconImage.width = 30
        iconImage.height = 30
        iconImage.image = UIImage(named:"avatar_vgirl")
        iconImage.isHidden = true
        return iconImage
        
    }()
}

// MARK: 重写layout方法
private class HomePictureViewlayout: UICollectionViewFlowLayout {
    
    override func prepare() {
       
        // 1.准备布局
        // 什么时候调用？ 1.先调用一个有 多少cell 2.调用准备布局，3.调用返回cell
        //itemSize = CGSize(width: 90, height: 90)
        minimumLineSpacing = 10
        minimumInteritemSpacing = 10
        scrollDirection = UICollectionViewScrollDirection.vertical
        
    }
}




